/**
 * 406. 根据身高重建队列
 * https://leetcode-cn.com/problems/queue-reconstruction-by-height/
 */
const { displayNestedArray } = require('../../libs/public');

/**
 * @param {number[][]} people
 * @return {number[][]}
 */
function reconstructQueue(people) {
  people.sort((a, b) => {
    if (a[0] === b[0]) {
      return b[1] - a[1];
    }
    return a[0] - b[0];
  });
  const indexes = new Array(people.length).fill(0);
  for (let i = 1; i < people.length; i += 1) {
    indexes[i] = i;
  }
  const result = new Array(people.length).fill(null);
  for (let i = 0; i < people.length; i += 1) {
    const [, count] = people[i];
    result[indexes[count]] = people[i];
    indexes.splice(count, 1);
  }
  return result;
}

console.log(displayNestedArray(reconstructQueue([[7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2]])) === '[[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]');
console.log(displayNestedArray(reconstructQueue([[6, 0], [5, 0], [4, 0], [3, 2], [2, 2], [1, 4]])) === '[[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]');
